package com.sig.util;

import com.sig.util.id.GameSnowflakeHolder;
import com.sig.util.id.SnowflakeHolder;

import java.util.UUID;

/**
 * ID生成工具
 *
 * @author sig
 * @since 2019/1/29
 */
public final class IdUtil {
    public static final String GAME_SERVER_ID_KEY = "gameserverid";
    public static final String APP_MACHINE_ID_KEY = "appmachineid";
    private static int gameServerId = Integer.parseInt(System.getProperty(GAME_SERVER_ID_KEY, "1"));
    private static int appMachineId = Integer.parseInt(System.getProperty(APP_MACHINE_ID_KEY, "1"));
    private static String mode = null;
    private static boolean useOldAlgorithm = false;

    private static GameSnowflakeHolder gameSnowflakeHolder = null;
    private static SnowflakeHolder snowflakeHolder = null;

    private IdUtil() {
    }

    public static void initAppMachineId(int appMachineId) {
            IdUtil.appMachineId = appMachineId;
        gameSnowflakeHolder = new GameSnowflakeHolder(appMachineId);
    }

    public static void initGameServerId(int gameServerId) {
        IdUtil.gameServerId = gameServerId;
    }

    public static void initGameServerMode(String mode) {
            IdUtil.mode = mode;
    }

    public static void useOldAlgorithm() {
        useOldAlgorithm = true;
        snowflakeHolder = new SnowflakeHolder(appMachineId);
    }

    public static int gameServerId() {
        return gameServerId;
    }

    public static String mode() {
        return mode;
    }

    public static String generateStringId() {
        return UUID.randomUUID().toString();
    }

    public static long generateLongId() {
        return useOldAlgorithm ? snowflakeHolder.generateLongId() : gameSnowflakeHolder.generateLongId();
    }

    public static long generateLongId(String catalog) {
        return useOldAlgorithm ? snowflakeHolder.generateLongId(catalog) : gameSnowflakeHolder.generateLongId(catalog);
    }

    public static long timestamp(long id) {
        return useOldAlgorithm ? snowflakeHolder.timestamp(id) : gameSnowflakeHolder.timestamp(id);
    }

    public static int gameServerId(long id) {
        return useOldAlgorithm ? snowflakeHolder.gameServerId(id) : gameSnowflakeHolder.gameServerId(id);
    }

    public static int sequence(long id) {
        return useOldAlgorithm ? snowflakeHolder.sequence(id) : gameSnowflakeHolder.sequence(id);
    }
}
